package com.jse;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;

public class Io {

	public static void close(AutoCloseable...acs) {
		try{
			for(var ac:acs) {
				if(ac==null) {
					
				}else if(ac instanceof Connection c) {
					if(c.getAutoCommit()){c.close();c=null;}//不是自动提交时不关闭
				}else{
					ac.close();ac=null;
				}
			}
		} catch (Exception e) {
			throw new RuntimeException("io close fail!");
		}
	}

	public static String read(InputStream in) {return readString(in);}
	public static String readString(InputStream in) {
		return new String(readBytes(in),StandardCharsets.UTF_8);
	}
	
	public static String read(Reader reader) {return readString(reader);}
	public static String readString(Reader reader) {
		try(reader){
			StringWriter sw=new StringWriter();
			reader.transferTo(sw);
			return sw.toString();
		} catch (IOException e) {
			throw new RuntimeException("io reader fail!");
		}
    }
	
	public static byte[] readSocketByte(InputStream in,int lenx) {
        byte[] b=new byte[lenx];//1024可改成任何需要的值  
    	try(BufferedInputStream is=new BufferedInputStream(in)){
    		is.read(b,0,lenx);
    	    return b;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
    }
	
	public static byte[] readBytes(InputStream in) {
        byte[] buffer = new byte[8192];
        int n = 0;
        try(ByteArrayOutputStream out = new ByteArrayOutputStream()){
        	while (-1 != (n = in.read(buffer))) {
                out.write(buffer, 0, n);
            }
            return out.toByteArray();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
    }
	

	public static void main(String[] args) throws FileNotFoundException {
		System.out.println(readString(new FileReader("d:/1.txt")));
	}
}
